package com.hzhc.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.hzhc.entity.VehicleReservation;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yycljsys
 * @description: Bease64文件上传
 * @author: wxk
 * @create: 2020-05-11 10:18
 **/
public class Base64FileUpload {

	public static Map<String, Object> uploadFileBase64(String base64Str, String upLoadPath) {
		Map<String, Object> map = new HashMap<>();
		String dataPrix = ""; // base64格式前头
		String data = "";// 实体部分数据
		if (StrUtil.isNotBlank(base64Str)) {
			String[] d = base64Str.split("base64,");// 将字符串分成数组
			if (d.length == 2) {
				dataPrix = d[0];
				data = d[1];
			} else {
				map.put("success", false);
				map.put("msg", "图片格式不正确");
				map.put("data", null);
				return map;
			}
			String suffix = "";// 图片后缀，用以识别哪种格式数据
			// 编码的jpeg图片数据
			if ("data:image/jpeg;".equalsIgnoreCase(dataPrix) || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {
				suffix = ".jpg";
			} else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
				// 编码的icon图片数据
				suffix = ".ico";
			} else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
				// 编码的gif图片数据
				suffix = ".gif";
			} else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
				// 编码的png图片数据
				suffix = ".png";
			} else if("data:application/pdf;".equalsIgnoreCase(dataPrix)){
				// data:application/pdf;base64,base64编码的pdf文件数据
				suffix = ".pdf";
			} else{
				map.put("success", false);
				map.put("msg", "请上传图片或者PDF文件类型");
				map.put("data", null);
				return map;
			}
			DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String dayFormat = LocalDate.now().format(formatters);
			String str = StrUtil.uuid();
			String newFileName = str + suffix;
			String imgFilePath = upLoadPath + File.separatorChar + dayFormat;
			try {
				// Base64解码
				byte[] b = Base64.decode(data);

				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {
						// 调整异常数据
						b[i] += 256;
					}
				}

				File dir = new File(imgFilePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				OutputStream out = new FileOutputStream(
						imgFilePath + File.separatorChar + newFileName + File.separatorChar);
				out.write(b);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "上传失败,服务器开小差");
				map.put("data", null);
				return map;
			}
			JSONObject object = new JSONObject();
			object.put("fileName", newFileName);
			object.put("dayFormat", dayFormat);
			map.put("success", true);
			map.put("msg", "上传成功");
			map.put("data", object);
			return map;
		}
		map.put("success", false);
		map.put("msg", "图片格式不正确");
		map.put("data", null);
		return map;
	}

	public static Map<String, Object> uploadCntrFileBase64(VehicleReservation vehicleReservation,String base64Str, String upLoadPath,String cntrNo) {
		Map<String, Object> map = new HashMap<>();
		String dataPrix = ""; // base64格式前头
		String data = "";// 实体部分数据
		if (StrUtil.isNotBlank(base64Str)) {
			String[] d = base64Str.split("base64,");// 将字符串分成数组
			if (d.length == 2) {
				dataPrix = d[0];
				data = d[1];
			} else {
				map.put("success", false);
				map.put("msg", "图片格式不正确");
				map.put("data", null);
				return map;
			}
			String suffix = "";// 图片后缀，用以识别哪种格式数据
			// 编码的jpeg图片数据
			if ("data:image/jpeg;".equalsIgnoreCase(dataPrix) || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {
				suffix = ".jpg";
			} else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
				// 编码的icon图片数据
				suffix = ".ico";
			} else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
				// 编码的gif图片数据
				suffix = ".gif";
			} else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
				// 编码的png图片数据
				suffix = ".png";
			} else if("data:application/pdf;".equalsIgnoreCase(dataPrix)){
				// data:application/pdf;base64,base64编码的pdf文件数据
				suffix = ".pdf";
			} else{
				map.put("success", false);
				map.put("msg", "请上传图片或者PDF文件类型");
				map.put("data", null);
				return map;
			}
			String str = StrUtil.uuid();
			String newFileName = str + suffix;
			String imgFilePath = upLoadPath + File.separatorChar + vehicleReservation.getOrderNo()+File.separatorChar+cntrNo;
			try {
				// Base64解码
				byte[] b = Base64.decode(data);

				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {
						// 调整异常数据
						b[i] += 256;
					}
				}

				File dir = new File(imgFilePath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				OutputStream out = new FileOutputStream(
						imgFilePath + File.separatorChar + newFileName + File.separatorChar);
				out.write(b);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "上传失败,服务器开小差");
				map.put("data", null);
				return map;
			}
			JSONObject object = new JSONObject();
			object.put("fileName", newFileName);
			object.put("path", vehicleReservation.getOrderNo()+"/"+cntrNo);
			map.put("success", true);
			map.put("msg", "上传成功");
			map.put("data", object);
			return map;
		}
		map.put("success", false);
		map.put("msg", "图片格式不正确");
		map.put("data", null);
		return map;
	}

	public static MultipartFile base64ToMultipartFile (String s) {
		MultipartFile image = null;
		StringBuilder base64 = new StringBuilder("");
		if (s != null && !"".equals(s)) {
			base64.append(s);
			String[] baseStrs = base64.toString().split(",");
			Base64 decoder = new Base64();
			byte[] b = new byte[0];
			b = Base64.decode(baseStrs[1]);
			for (int j = 0; j < b.length; ++j) {
				if (b[j] < 0) {
					b[j] += 256;
				}
			}
			image =  new BASE64DecodedMultipartFile(b, baseStrs[0]);
		}
		return image;
	}
}
